<template>
    <div class="process-monitoring-box1">
        <div class="resource-library-type-table">
            <div class="resource-library-type" style="width: 30%;overflow-x: auto;" v-show="classEelement">
                <div style="padding:5px 0 0 5px;display: flex;justify-content: space-between;">
                    <div>
                        <!-- @click="treeOperation(true)" @click="treeOperation(false)" -->
                        <a-button style="height: 25px !important;" @click="$refs.xTree.setAllTreeExpand(true)" ghost ><a-icon style="font-size: 16px;" type="caret-down" theme="filled" />展开</a-button>
                        <a-button style="margin-left: 5px;height: 25px !important;" @click="$refs.xTree.clearTreeExpand()" ghost><a-icon style="font-size: 16px;" type="caret-up" theme="filled" />收起</a-button>
                    </div>
                    <div>
                        <a-button style="margin-left: 5px;height: 25px !important;" @click="zkClassEelement(false)" ghost><a-icon style="font-size: 16px;" type="caret-up" theme="filled" />隐藏分类</a-button>
                    </div>
                </div>
                <vxe-table
                    class="tree-vxetable-box"
                    resizable
                    ref="xTree"
                    :show-header="false"
                    :tree-config="{transform: true, rowField: 'id', parentField: 'parentId',iconClose:'vxe-icon-square-plus-fill',iconOpen:'vxe-icon-square-minus-fill'}"
                    :radio-config="{labelField: 'name'}"
                    :data="treeTypeList"
                    :row-config="{isCurrent: true, isHover: true}"
                    @current-change="currentChangeEvent"
                    @cell-click="cellClick"
                >
                <!-- @click="$refs.xTree.clearCurrentRow()" -->
                    <vxe-column field="name" title="name" tree-node>
                        <template #default="{ row }">
                            <span>
                                <template v-if="!row.parentId || row.children && row.children.length">
                                    <a-icon style="font-size: 16px;color: #ffa500;" :type="$refs.xTree.isTreeExpandByRow(row) ? 'folder-open' : 'folder'" theme="filled"></a-icon>
                                </template>
                                <template v-else>
                                    <i class="tree-node-icon vxe-icon-file-txt"></i>
                                </template>
                                <span>{{ row.name }}</span>
                            </span>
                        </template>
                    </vxe-column>
                </vxe-table>
                <!-- <a-tree
                    :key="treeKey"
                    v-if="treeTypeList.length>0"
                    :show-line="true"
                    :show-icon="true"
                    :tree-data="treeTypeList"
                    :replaceFields='replaceFields'
                    v-model:selectedKeys="selectedKeys"
                    :default-expand-all="defaultExpandAll"
                    :defaultSelectedKeys="selectedKeys"
                    @select="treeChange"
                >
                    <a-icon slot="parentLevel" type="folder-open" theme="filled" style="font-size: 16px;color: #ffa500;" />
                    
                </a-tree> -->
                <!-- <a-icon slot="childLevel" type="file" theme="filled" style="font-size: 16px;color: #ffa500;" /> -->
                <!-- v-model:selectedKeys="selectedKeys" -->
            </div>
            <div v-show="!classEelement">
                <a-button style="margin-left: 5px;height: 25px !important;" @click="zkClassEelement(true)" ghost><a-icon style="font-size: 16px;" type="caret-up" theme="filled" />展开分类</a-button>
            </div>
            <div class="resource-library-table">
                <commpVxeTable
                :key="dataTableKey"
                :config="dataTableConfig" 
                :columns="columnsVxe" 
                :formItem="formItem"
                :isCanWrap="true"
                ref="acceptanceRegistrationRef"
                @searchEvent="searchEvent"
                @resetEvent="resetEvent"
                @checkboxChange="checkboxChange"
                >
                    <!-- <template v-slot:ftype_time="{data}"  >
                        <a-tree-select
                            v-model:value="ftype"
                            :expandedKeys="expandedKeys" 
                            :tree-data="treeTypeList" 
                            :replaceFields='replaceFields'
                            style="width: 180px"
                            placeholder="请选择分类"
                            allow-clear
                            tree-default-expand-all
                            @change="treeChange"
                        />
                    </template> -->
                    <template v-slot:externalOperations="{data}"  >
                        <vxe-form-item>
                            <template>
                                <a-button class="blue-btn" type="primary" @click="newlyAddedClick()" icon="plus">新增</a-button>
                            </template>
                        </vxe-form-item>
                        <vxe-form-item>
                            <template>
                                <a-button class="blue-btn" type="primary" @click="downloadControlClick()" icon="setting">下载控制</a-button>
                            </template>
                        </vxe-form-item>
                        <vxe-form-item>
                            <template>
                                <a-button class="blue-btn" type="primary" @click="sealFileClick()" icon="audit">盖章</a-button>
                            </template>
                        </vxe-form-item>
                        <vxe-form-item>
                            <template>
                                <a-button class="red-btn" type="primary" @click="batchDelete()" icon="delete">批量删除</a-button>
                            </template>
                        </vxe-form-item>
                        <vxe-form-item>
                            <template>
                                <a-button class="green-btn" type="primary" @click="batchDownload()" icon="download">批量下载</a-button>
                            </template>
                        </vxe-form-item>
                        <!-- <vxe-form-item>
                            <template>
                                <a-upload style="display: inline-block;" :beforeUpload="$event=>{return false}" action="" @change="importClick">
                                    <a-button class="blue-btn" type="default"  icon="import">导入</a-button>
                                </a-upload>
                            </template>
                        </vxe-form-item> -->
                        <vxe-form-item>
                            <template>
                                <a-button class="blue-btn" type="primary" :loading="leadingOutLoading" @click="exportClick()" icon="export">导出</a-button>
                            </template>
                        </vxe-form-item>
                        <!-- <vxe-form-item>
                            <template>
                                <a-button class="green-btn" type="primary" :loading="DownloadTemplateLoading" @click="downloadTemplate()" icon="download">下载模板</a-button>
                            </template>
                        </vxe-form-item> -->
                    </template>
                    <template v-slot:fwjmc_name="{row}">
                        <div class="quality-system-fwjmc">
                            <span v-if="row.fxdzt" class="fxdzt-name" :class="row.fxdzt=='修订'?'orange-v':(row.fxdzt=='修改'?'yellow-v':(row.fxdzt=='作废'?'red-v':''))">{{ row.fxdzt }}</span>
                            <a @click="viewClick(row)">{{ row.fwjmc }}</a>
                        </div>
                    </template>
                    <template v-slot:operation_btn="{row}" data-desc="自定操作栏">
                        <a-form layout="inline" class="search-form" >
                            <!-- <a-form-item >
                                <a-button class="blue-btn" type="primary" @click="initialization(row)">初始化</a-button>
                            </a-form-item> -->
                            <a-form-item >
                                <a-button class="blue-btn" type="primary" @click="editClick(row)" icon="edit">编辑</a-button>
                            </a-form-item>
                            <a-form-item >
                                <a-button class="red-btn" type="primary" @click="deleteClick(row)" icon="delete">删除</a-button>
                            </a-form-item>
                            <a-form-item v-if="row.fwjlx">
                                <a-button class="green-l-btn" type="primary" @click="downloadClick(row)" icon="download">下载</a-button>
                            </a-form-item>
                        </a-form>
                    </template>
                </commpVxeTable>
            </div>
        </div>
        <increase ref="increaseRef" @successClick="successClick"/>
        <serverEditingView ref="serverEditingViewRef" @refreshChange="$event=>{}"/>
        <sealFile ref="sealFileRef" @refreshSealFile="refreshSealFile" />
        <downloadControl ref="downloadControlRef" @refreshSealFile="refreshSealFile" />
    </div>
</template>
<script>
import assessCheckApi from './service/api'
import increase from './increase.vue'
import commpVxeTable from '@/components/commp-vxe-table/commp-vxe-table.vue'
import blobType from '@/common/blobType'
import moment from 'moment'
import { deleteBatch, downloadFile,
leadingInExccel,
leadingOutExccel,
leadingOutFormwork,downloadZipFile } from './service/index'
import {
    initZltxwjFlow,
    queryTreeList,
} from './service/index'
// import serverEditingView from '@/components/comp-model-series/server-editing-view'
import serverEditingView from './viesFile.vue'
import sealFile from './sealFile.vue'
import downloadControl from './downloadControl.vue'
function addParentId(nodes, parentId = null) {
  nodes.forEach(node => {
    node.id = node.key
    node.parentId = parentId;
    if (node.children && node.children.length > 0) {
      addParentId(node.children, node.key);
    }
  });
}
export default {
    components:{
        commpVxeTable,
        increase,
        serverEditingView,
        sealFile,
        downloadControl,
    },
    props:{

    },
    data(){
        return{
            ftype:undefined,
            replaceFields: {
                children: 'children', //后端数组层级的名字
                key: 'value', //一般是id
                title: 'value',
            },
            treeTypeList:[],
            selectedKeys: [],
            formItem:[
                {
                    label: '文件名称',
                    model: 'fwjmc',
                },{
                    label: '文件编号',
                    model: 'fwjbh',
                }
                // ,{
                //     label: '分类',
                //     model: 'ftype',
                //     slotName:'ftype_time'
                // }

            ],//
            columnsVxe:[{ 
                type: 'checkbox', 
                width: 60 ,
                fixed: 'left'
            },{
                title: '文件名称', //列头显示文字
                field: 'fwjmc',
                slots: {
                    default: 'fwjmc_name',
                },
            },{
                title: '分类',
                field: 'ftype',
                titleInterval:true,
                slots: {
                    header:'ftype_header',
                },
                width:105,
            },{
                title: '状态',
                field: 'fzt',
                titleInterval:true,
                slots: {
                    header:'fzt_header',
                },
                width:105,
            },{
                title: '操作',
                field: 'id',
                titleInterval:true,
                slots: {
                    // 使用插槽模板渲染
                    default: 'operation_btn',
                    header:'operation_header',
                },
                width:265
                // visible:!this.parameter.isReadOnly
            }],
            columnsVxe1:[
            { 
                type: 'checkbox', 
                width: 60 ,
                fixed: 'left'
            },{
                title: '序号', //列头显示文字
                field: 'forder',
                width: 52,
            },{
                title: '文件名称', //列头显示文字
                field: 'fwjmc',
                slots: {
                    default: 'fwjmc_name',
                },
            },{
                title: '分类',
                field: 'ftype',
                titleInterval:true,
                slots: {
                    header:'ftype_header',
                },
                width:105,
            },{
                title: '文件编号',
                field: 'fwjbh',
                width:110,
            },{
                title: '修改次数',
                field: 'fxgcs',
                width:77,
            },{
                title: '实施日期',
                field: 'fssrq',
                width:105,
            }
            // ,{
            //     title: '上传日期',
            //     field: 'fscrq',
            // }
            ,{
                title: '状态',
                field: 'fzt',
                titleInterval:true,
                slots: {
                    header:'fzt_header',
                },
                width:105,
            },{
                title: '操作',
                field: 'id',
                titleInterval:true,
                slots: {
                    // 使用插槽模板渲染
                    default: 'operation_btn',
                    header:'operation_header',
                },
                width:265
                // visible:!this.parameter.isReadOnly
            }],
            columnsVxe2:[{ 
                type: 'checkbox', 
                width: 60 ,
                fixed: 'left'
            },{
                title: '文件名称', //列头显示文字
                field: 'fwjmc',
                slots: {
                    default: 'fwjmc_name',
                },
            },{
                title: '分类',
                field: 'ftype',
                titleInterval:true,
                slots: {
                    header:'ftype_header',
                },
                width:105,
            },{
                title: '状态',
                field: 'fzt',
                titleInterval:true,
                slots: {
                    header:'fzt_header',
                },
                width:105,
            },{
                title: '操作',
                field: 'id',
                titleInterval:true,
                slots: {
                    // 使用插槽模板渲染
                    default: 'operation_btn',
                    header:'operation_header',
                },
                width:265
                // visible:!this.parameter.isReadOnly
            }],
            dataTableKey:null,
            dataTableConfig:{
                api: assessCheckApi.list,
                rowId: 'id',
                paramet:{
                    fzt:'现行有效'
                }
            },
            selectIdArr:[],
            DownloadTemplateLoading:false,
            leadingOutLoading:false,
            searchFrom:{},
            treeKey:null,
            defaultExpandAll:true,
            currentGlData:{},
            classEelement:true,
            currentTreeD:[],
        }
    },
    watch:{

    },
    mounted(){
        queryTreeList().then(res => {
            if (res.code == 200){
                addParentId(res.result)
                // this.treeTypeList = res.result;
                // this.treeParentClick(res.result)
                res.result.forEach(item=>{
                    this.getTreeItem(item)
                })
                this.currentTreeD = res.result
                //console.log('树的结构',this.treeTypeList)

            }
        })
    },
    created(){
        //console.log('我在执行')
    },
    methods:{
        getTreeItem(item){
            this.treeTypeList.push({
                id:item.id,
                key:item.key,
                parentId:item.parentId,
                name:item.value,
                children:item.children

            })
            if(item.children && item.children.length>0){
                item.children.forEach(trem=>{
                   this.getTreeItem(trem) 
                })
            }
        },
        currentChangeEvent({row}){
            //console.log('获取高亮行',row)
            
            this.ftype = row.name
            this.dataTableConfig.paramet = {
                ...this.dataTableConfig.paramet,
                ftype:row.name,
                ftypeid:row.id,
            }
            this.successClick()
            this.searchFrom['ftype'] = row.name
        },
        cellClick({row}){
            //console.log('我选中什么1',row.id)
            //console.log('我选中什么2',this.currentGlData.id)
            if(row.id == this.currentGlData.id){
                this.$refs.xTree.clearCurrentRow()
                this.currentGlData = {}
                this.ftype = ''
                this.dataTableConfig.paramet = {
                    ...this.dataTableConfig.paramet,
                    ftype:'',
                    ftypeid:'',
                }
                this.successClick()
                this.searchFrom['ftype'] = ''
            }else{
                this.currentGlData = row
            }
            
        },
        zkClassEelement(val){
            //console.log(val)
            this.classEelement = val
            if(val){
                this.columnsVxe = this.columnsVxe2
            }else{
                this.columnsVxe = this.columnsVxe1
            }
            this.dataTableKey = Date.now()
        },
        viewClick(val){
            this.$refs.serverEditingViewRef.getData({id:val.id,type:'质量体系文件资源库',fwjlx:'.pdf'})
            this.$refs.serverEditingViewRef.visibleShow = true
        },
        downloadControlClick(){//下载控制
            if(this.selectIdArr.length){
                this.$refs.downloadControlRef.getData({ids:this.selectIdArr.join(',')})
                this.$refs.downloadControlRef.visibleShow = true
            }else{
                this.$message.warning('请先选择需要下载控制项')
            }
        },
        sealFileClick(){//盖章
            if(this.selectIdArr.length){
                this.$refs.sealFileRef.getData({ids:this.selectIdArr.join(',')})
                this.$refs.sealFileRef.visibleShow = true
            }else{
                this.$message.warning('请先选择需要盖章项')
            }
            
        },
        refreshSealFile(){
            this.dataTableKey = Date.now()
        },
        treeOperation(val){
            this.defaultExpandAll = val
            this.treeKey = Date.now()
        },
        successClick(){
            this.$refs.acceptanceRegistrationRef.searchEvent()
        },
        treeChange(val){
            //console.log(val)
            this.selectedKeys = val
            this.ftype = val.length?val[0]:''
            this.dataTableConfig.paramet = {
                ...this.dataTableConfig.paramet,
                ftype:val.length?val[0]:''
            }
            this.successClick()
            this.searchFrom['ftype'] = val.length?val[0]:''
        },
        searchEvent(searchFrom){//搜索
            // this.dataTableConfig.paramet = {
            //     ...this.dataTableConfig.paramet,
            //     ftype:this.ftype?this.ftype:''
            // }
            this.searchFrom = {...searchFrom,...this.dataTableConfig.paramet}
            // //console.log(this.dataTableConfig.paramet)
        },
        resetEvent(){//重置
            // this.dataTableConfig.paramet = {
            //     ...this.dataTableConfig.paramet,
            // }
            // this.ftype = undefined
            // this.searchFrom = {}
        },
        initialization(val){
            var that = this
            this.$confirm({
                title:'您确认要初始化吗？',
                // icon: createVNode(ExclamationCircleOutlined),
                onOk() {
                    initZltxwjFlow({id:val.id}).then(res=>{
                        if(res.code == 200){
                            that.$message.success(res.message)
                            that.$refs.acceptanceRegistrationRef.searchEvent()
                            // resetEvent
                        }else{
                            that.$message.warning(res.message)
                        }
                    })
                },
                
            });
            
        },
        newlyAddedClick(){
            this.$refs.increaseRef.getData({ftypeid:this.currentTreeD[0].id,fzt:'现行有效',funIndex:0,title:'新增'},this.currentTreeD)
            this.$refs.increaseRef.visibleShow = true
        },
        checkboxChange(row){
            this.selectIdArr = []
            row.forEach(item => {
                this.selectIdArr.push(item.id)
            });
        },
        batchDelete(){
            var that = this
            if(this.selectIdArr.length){
                this.$confirm({
                    title:'您确认要删除吗？',
                    onOk() {
                        deleteBatch({ids:that.selectIdArr.join(',')}).then(res=>{
                            if(res.code == 200){
                                that.$message.success(res.message)
                                that.$refs.acceptanceRegistrationRef.searchEvent()
                            }else{
                                that.$message.warning(res.message)
                            }
                        })
                    }
                })
            }else{
                this.$message.warning('请选择删除项')
            }
        },
        importClick({file}){
            var that = this
            if(typeof file.uid !== 'undefined') {
                if(file.name.indexOf(".xls") !== -1 || file.name.indexOf(".xlsx") !==-1) {
                    const fileData = new FormData();
                    fileData.append("file",file);
                    leadingInExccel(fileData).then(res => {
                        that.renovateSearchTabel()
                        that.$message.success('导入成功')
                    }).catch(error =>{
                        that.$message.success('导入失败')
                    })
                }else{
                    this.$message.warning('请导入正确的文件类型')
                }
                
            }
        },
        exportClick(){//导出
            var that = this
            this.leadingOutLoading = true
            var fileName = '质量体系文件模板'
            let param = { }
            if(that.selectIdArr.length){
                param = {
                    ids:that.selectIdArr.join(',')
                }
            }else{
                param = this.searchFrom
            }
            
            leadingOutExccel(param).then((data) => {
                this.leadingOutLoading = false
                if (!data) {
                    that.$message.warning('文件下载失败')
                    return
                }
                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
                } else {
                    let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
                    let link = document.createElement('a')
                    link.style.display = 'none'
                    link.href = url
                    link.setAttribute('download', fileName + '.xls')
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link) //下载完成移除元素
                    window.URL.revokeObjectURL(url) //释放掉blob对象
                }
            })

        },
        batchDownload(){//批量下载
            if(!this.selectIdArr.length){
                this.$message.warning('请选择下载项')
                return false
            }
            var that = this
            this.downloadFileLoading = true
            var fileName = '质量体系文件.zip'
            //console.log(fileName)
            let param = {ids:this.selectIdArr.join(',')}
            
            downloadZipFile(param).then((data) => {
                this.downloadFileLoading = false
                if (!data) {
                    that.$message.warning('文件下载失败')
                    return
                }
                let url = window.URL.createObjectURL(new Blob([data]), { type: blobType.type[blobType.suffix.indexOf('.zip')] })
                let link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download', fileName)
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link) //下载完成移除元素
                window.URL.revokeObjectURL(url) //释放掉blob对象
            })
        },
        downloadTemplate(){
            var that = this
            this.DownloadTemplateLoading = true
            var fileName = '质量体系文件模板'
            let param = {}
            
            leadingOutFormwork(param).then((data) => {
                this.DownloadTemplateLoading = false
                if (!data) {
                    that.$message.warning('文件下载失败')
                return
                }
                // if (typeof window.navigator.msSaveBlob !== 'undefined') {
                //     window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }))
                // } else {
                    let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
                    let link = document.createElement('a')
                    link.style.display = 'none'
                    link.href = url
                    link.setAttribute('download', fileName + '.xls')
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link) //下载完成移除元素
                    window.URL.revokeObjectURL(url) //释放掉blob对象
                // }
            })
        },
        editClick(val){
            this.$refs.increaseRef.getData({...val,funIndex:0,title:'编辑'},this.currentTreeD)
            this.$refs.increaseRef.visibleShow = true
        },
        deleteClick(val){
            var that = this
            this.$confirm({
                title:'您确认要删除吗？',
                onOk() {
                    deleteBatch({ids:val.id}).then(res=>{
                        if(res.code == 200){
                            that.$message.success(res.message)
                            that.$refs.acceptanceRegistrationRef.searchEvent()
                        }else{
                            that.$message.warning(res.message)
                        }
                    })
                }
            })
        },
        downloadClick(val){
            //console.log(val)
            if(!val.fwjlx){
                this.$message.warning('当前暂无文件')
                return false
            }
            //console.log(val)
            var that = this
            this.downloadFileLoading = true
            var fileName = val.fwjmc+val.fwjlx
            //console.log(fileName)
            let param = {id: val.id}
            
            downloadFile(param).then((data) => {
                this.downloadFileLoading = false
                if (!data) {
                    that.$message.warning('文件下载失败')
                    return
                }
                let url = window.URL.createObjectURL(new Blob([data]), { type: blobType.type[blobType.suffix.indexOf(val.fwjlx)] })
                let link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download', fileName)
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link) //下载完成移除元素
                window.URL.revokeObjectURL(url) //释放掉blob对象
            })
        },
    }
}
</script>
<style lang="less">
.quality-system-fwjmc{
    // display: flex;
    // align-items: center;
    .fxdzt-name{
        // display: inline-block;
        margin-left: 3px;
        color: #fff;
        padding: 0 3px;
        font-size: 12px;
        border-radius: 2px;
        background-color: #a5a1a1;
    }
    .orange-v{
        background: orange;
    }
    .yellow-v{
        background: yellow;
    }
    .red-v{
        background: red;
    }
    


}
.process-monitoring-box1{
    .resource-library-type-table{
        display: flex;
        width: 100%;
        align-items: flex-start;
        background-color: #fff;
        .resource-library-type{
            // margin-top: 110px;
            width: 180px;
            height: calc(100vh - 116px);
            overflow-x: hidden;
            overflow-y: auto;
            .ant-tree li .ant-tree-node-content-wrapper{
                padding: 0 !important;
            }
            .ant-tree-title{
                // font-weight: 600;
                color: #000;
            }
        }
        .resource-library-table{
            flex: 1;
        }
    }
}
</style>